package com.xxxx.yoyo.adminweb;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxx.yoyo.bean.Admin;
import com.xxxx.yoyo.service.IAdminService;
import com.xxxx.yoyo.service.impl.AdminServiceImpl;
import com.xxxx.yoyo.util.SafeUtil;


@WebServlet("/admin/adminRe")
public class ModifyPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IAdminService adminService = new AdminServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置导航条上的[修改面]处于选中状态
		request.setAttribute("flag",5);
		
		//请求转发，跳转到/admin/admin reset.jsp页面
		request.getRequestDispatcher("/admin/admin_reset.jsp").forward(request,response);
	
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式为UTF-8,---解决巾文参数乱码
		request.setCharacterEncoding("UTF-8");
		
		//获取前端页面传递的参数id,username,password,passwordNew
		String adminIdstr = request.getParameter("id");
		int adminId = Integer.parseInt (adminIdstr);
		String password = request.getParameter("password");	//明文
		String passwordNew = request.getParameter ("passwordNew"); //明文
		
		//根据管理员id查询管理员
		Admin admin = adminService.getAdminById (adminId);
		//获取管理员的密码
		String currentPwd = admin.getPassword ();
		
		//对输入的旧密码进行加密
		String pwd = SafeUtil.encode (password);
		
		//判断旧密码是否正确
		if(currentPwd.equals(pwd)){//如果旧密码正确
			//更新用户的密码
			admin.setPassword(SafeUtil.encode(passwordNew));
			//更新数据库-adminService去更新
			adminService.updateAdmin (admin);
			//更新session中的admin
			HttpSession session = request.getSession ();
			session.setAttribute ("admin", admin);
			//提示成功信息
			request.setAttribute("msg","密码修改成功！");
		
		}else {//旧密码错误
			//提示错误
			request.setAttribute("msg","修改密码失败！原密码输入错误！");
			
		}
		//设置导航条上的[修改密码]处于选中状态
		request.setAttribute ("flag",5);
		//跳转到修改密码页面/admin/admin reset·jsp
		request.getRequestDispatcher ("/admin/admin_reset.jsp").forward (request,response);

	}

}
